import { activeAnalysis, pageCuesActive } from '@/services/api/api-cues-active';
import { searchTreeOrganization } from '@/services/api/api-cues-submit';
import {
  FileImageOutlined,
  MenuFoldOutlined,
  PaperClipOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import {
  LightFilter,
  PageContainer,
  ProCard,
  ProColumns,
  ProFormCascader,
  ProFormDateRangePicker,
} from '@ant-design/pro-components';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Button, Cascader, Input, Popover, Space, Spin, Tag } from 'antd';
import { DefaultOptionType } from 'antd/lib/select';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddActive from './components/AddActive';
import CuesSubmitList from './components/CuesSubmitList';
import DetailsActive from './components/DetailsActive';
import ReceiptActive from './components/ReceiptActive';
import SubmitPool from './components/SubmitPool';
import WordImport from './components/WordImport';
import style from './index.less';
import { findTagColor } from '@/utils/findTagColor';
const Active: React.FC = () => {
  const access = useAccess();

  const [width, setWidth] = useState(500);

  const actionRef = useRef<ActionType>();

  const [articleOrganizations, setArticleOrganizationState] = useState<any[]>([]);

  const [showList, setShowListState] = useState(false);



  const onSearch = () => { };
  //线索列表
  const content = (
    <div style={{ display: 'flex' }}>
      {showList ? (
        <div style={{ width: 500 }}>
          {/* <Search placeholder="input search text" onSearch={onSearch} enterButton /> */}
          <CuesSubmitList
            onRefurbish={() => {
              actionRef?.current?.reset();
            }}
          />
        </div>
      ) : (
        <></>
      )}
      <div>
        <MenuFoldOutlined
          onClick={() => setShowListState(!showList)}
          style={{
            fontSize: 22,
            backgroundColor: showList ? '#E6E6E6' : '',
            height: 30,
            width: 30,
            borderRadius: 5,
            padding: 5,
          }}
        />
      </div>
      <div style={{ width: 320, padding: '0px 20px' }}>
        <AddActive
          key="add_active"
          onRefurbish={() => {
            actionRef?.current?.reset();
          }}
          triggerMode="card"
        />
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <SubmitPool
            onRefurbish={() => {
              actionRef?.current?.reset();
            }}
          />
          <WordImport
            onInit={(editor) => { }}
            onRefurbish={() => {
              actionRef?.current?.reset();
            }}
            readonly={false}
            onClick={(value) => { }}
            defaultContent=""
          />
        </div>
      </div>
    </div>
  );
  /**
   * 加载 单位 列表
   * @param key
   */
  const treeOrganizationData = async () => {
    try {
      const response = await searchTreeOrganization();
      if (response.code === 0) {
        setArticleOrganizationState(response.data);
      }
    } catch (error) { }
  };

  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});
  const [loading, setLoadingState] = useState(true);
  const [responsive, setResponsive] = useState(false);
  const [totalData, setTotalDataState] = useState<CuesActiveData.Analysis>();
  useEffect(() => {
    treeOrganizationData();
    analysisData();
  }, []);
  /**
   * 加载 单位 列表
   * @param key
   */
  const analysisData = async () => {
    try {
      const response = await activeAnalysis();
      if (response.code === 0) {
        console.log(response.data);
        setLoadingState(false);
        setTotalDataState(response.data);
      }
    } catch (error) { }
  };

  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  const columns: ProColumns<CuesActiveData.ActivePage>[] = [
    {
      title: '报送线索',
      dataIndex: 'articleName',
      // copyable: true,
      search: false,
      ellipsis: true,
      width: '300px',
      align: 'center',
      key: 'articleName',
      render: (dom, record, _index, action) => {
        return (
          <div
            style={{
              textAlign: 'left',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
            }}
          >
            {record.isImage === 1 ? <FileImageOutlined /> : <></>}
            {record.isFile === 1 ? <PaperClipOutlined /> : <></>}
            <DetailsActive
              id={record.id}
              name={record.articleName}
              onRefurbish={() => {
                actionRef?.current?.reload();
              }}
            />
          </div>
        );
      },
    },
    {
      title: '单位',
      key: 'articleOrganizationAvatar',
      dataIndex: 'articleOrganizationAvatar',
      width: '180px',
      align: 'center',
      search: false,
      valueType: 'avatar',
      render: (dom, row) => (
        <div
          style={{
            textAlign: 'left',
            marginLeft: '24px',
          }}
        >
          <Tag color={findTagColor(row.articleOrganizationTopName)}>
            {row.articleOrganizationTopName}
          </Tag>
          <span>{dom}</span>
          {row.articleOrganizationName}
        </div>
      ),
    },
    {
      title: '行业',
      dataIndex: 'articleIndustryName',
      key: 'articleIndustryName',
      width: '80px',
      align: 'center',
      search: false,
      render: (_, row) => {
        let industrys = row?.articleIndustrys;

        if (industrys.length > 2) {
          industrys = industrys.slice(0, 2);
          industrys.push({
            label: '...',
            value: '...',
          });
        }

        return (
          <Space size={[0, 8]} wrap>
            {industrys?.map(
              (item) =>
                // <Tag key={item.value}>{item.label}</Tag>
                item.label,
            )}
          </Space>
        );
      },
    },
    {
      title: '标签',
      dataIndex: 'articleLabels',
      key: 'articleLabels',
      width: '200px',
      align: 'center',
      search: false,
      render: (_, row) => {
        let labels = row?.articleLabels;

        if (labels.length > 2) {
          labels = labels.slice(0, 2);
          labels.push({
            label: '...',
            value: '...',
          });
        }
        return (
          <Space size={[0, 8]} wrap>
            {labels?.map((item) => (
              <Tag key={item.value}>{item.label}</Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: '新闻联络人',
      dataIndex: 'articleAccountName',
      // copyable: true,
      ellipsis: true,
      search: false,
      width: '100px',
      align: 'center',
      key: 'articleAccountName',
    },
    {
      title: '阅读情况',
      hideInSearch: true,
      hideInTable: !access.线索征集x配置x管理员,
      dataIndex: 'receipt',
      key: 'receipt',
      valueType: 'avatar',
      width: '80px',
      align: 'center',
      search: false,
      render: (dom, record) => {
        return <ReceiptActive id={record.id} receipt={record.receipt} />;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: '120px',
      align: 'center',
      search: false,
    },
    {
      title: '报送日期',
      dataIndex: 'createdTimes',
      key: 'createdTimes',
      valueType: 'dateRange',
      hideInTable: true,
      fieldProps: {
        allowClear: true,
        placeholder: ['开始日期', '结束日期'],
        format: 'YYYY-MM-DD',
        ranges: {
          今日: [moment(), moment()],
          本月: [moment().startOf('month'), moment().endOf('month')],
          上月: [
            moment().startOf('month').subtract(1, 'months'),
            moment().endOf('month').subtract(1, 'months'),
          ],
          最近7天: [moment().subtract(6, 'days'), moment()],
          最近60天: [moment().subtract(59, 'days'), moment()],
          最近90天: [moment().subtract(89, 'days'), moment()],
        },
      },
    },
  ];

  return (
    <PageContainer
      header={{
        title: (
          <span
            style={{
              marginInlineEnd: '12px',
              color: 'rgba(0, 0, 0, 0.88)',
              fontWeight: 600,
              fontSize: 20,
              height: 48,
              paddingRight: 35,
            }}
            title="主动报送"
          >
            主动报送
          </span>
        ),
        breadcrumb: {
          items: [],
        },
        style: {
          paddingBlockEnd: 0,
        },
        extra: [
          access.主动报送x上报线索x页面 && (
            // <AddActive
            //   key="add_active"
            //   onRefurbish={() => {
            //     actionRef.current?.reload();
            //   }}
            // />
            <Popover content={content} placement="bottomLeft" arrow={false} trigger="click">
              <Button type="primary">
                {' '}
                <PlusOutlined />
                报送线索
              </Button>
            </Popover>
          ),
        ],
      }}
    >
      {!access.线索征集x配置x提供者 && (
        <Spin spinning={loading} size="large">
          <ProCard
            headerBordered={false}
            bordered={false}
            direction={'column'}
            ghost
          >
            <ProCard
              headerBordered={false}
              bordered={false}
              className={style.topic}
              split={responsive ? 'horizontal' : 'vertical'}
              style={{ padding: '10px 40px', width: '95%' }}
            >
              {access.线索征集x配置x媒体需求者 && (
                <div>
                  <h3>线索报送总量</h3>
                  <h2 style={{ color: '#467BE3' }}>{totalData?.countCountyActive} </h2>
                </div>
              )}
              {access.线索征集x配置x管理员 && (
                <div>
                  <h3>线索报送总量</h3>
                  <div style={{ display: 'flex' }}>
                    <ProCard
                      bordered={false}
                      split={responsive ? 'horizontal' : 'vertical'}
                      style={{ padding: '10px 40px', width: '90%' }}
                    >
                      <span>市级部门</span>
                      <h2 style={{ color: '#467BE3' }}>{totalData?.countMunicipalActive}</h2>
                    </ProCard>
                    <ProCard
                      bordered={false}
                      split={responsive ? 'horizontal' : 'vertical'}
                      style={{ padding: '10px 40px', width: '90%', marginLeft: 10 }}
                    >
                      <span>区县部门</span>
                      <h2 style={{ color: '#467BE3' }}>{totalData?.countCountyActive}</h2>
                    </ProCard>
                  </div>
                </div>
              )}
            </ProCard>
            <ProCard
              bordered={false}
              className={style.submit}
              split={responsive ? 'horizontal' : 'vertical'}
              style={{ padding: '10px 40px', width: '95%' }}
            >
              {access.线索征集x配置x媒体需求者 && (
                <div>
                  <h3>报送单位总量</h3>
                  <h2 style={{ color: '#467BE3' }}>{totalData?.countCountyOrganization} </h2>
                </div>
              )}
              {access.线索征集x配置x管理员 && (
                <div>
                  <h3>报送单位总量</h3>
                  <div style={{ display: 'flex' }}>
                    <ProCard
                      bordered={false}
                      split={responsive ? 'horizontal' : 'vertical'}
                      style={{ padding: '10px 40px', width: '90%' }}
                    >
                      <span>市级部门</span>
                      <h2 style={{ color: '#467BE3' }}>
                        {totalData?.countMunicipalOrganization}
                      </h2>
                    </ProCard>
                    <ProCard
                      bordered={false}
                      split={responsive ? 'horizontal' : 'vertical'}
                      style={{ padding: '10px 40px', width: '90%', marginLeft: 10 }}
                    >
                      <span>区县部门</span>
                      <h2 style={{ color: '#467BE3' }}>{totalData?.countCountyOrganization}</h2>
                    </ProCard>
                  </div>
                </div>
              )}
            </ProCard>
            <ProCard
              bordered={false}
              className={style.active}
              split={responsive ? 'horizontal' : 'vertical'}
              style={{ padding: '10px 40px', width: '95%' }}
            >
              <h3>7天报送分析</h3>
              {/* <TinyArea
                  style={{ height: 100 }}
                  autoFit={true}
                  smooth
                  areaStyle={{
                    fill: 'l(270) 0:rgb(151 95 228 / 10%) 0.5:rgb(151 95 228 / 60%) 1:rgb(151 95 228)',
                  }}
                  line={{
                    color: '#975FE4',
                  }}
                  tooltip={{
                    customContent: (x, data) => {
                      if (x != null) {
                        return `${totalData?.cuesAnalysisLabelSos[x]?.label}: ${data[0].value}`;
                      } else {
                        return '';
                      }
                    },
                  }}
                  data={totalData ? totalData?.cuesAnalysisLabelSos.map((item) => item.value) : []}
                // data={[0, 0, 0, 0, 31]}
                /> */}
            </ProCard>
          </ProCard>
        </Spin>
      )}

      <ProTable<CuesActiveData.ActivePage>
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => {
          if (params.organizationIds) {
            const organizationParentIds: string[] = [];
            let organizationIds: string[] = [];

            params.organizationIds.forEach((item: string | any[]) => {
              if (item.length === 1) {
                organizationParentIds.push(item[0]);
              } else if (item.length > 1) {
                organizationIds.push(item[1]);
              }
            });
            organizationParentIds.forEach((id) => {
              const ids = articleOrganizations.find((item) => item.id === id).children;
              organizationIds = organizationIds.concat(ids.map((item: any) => item.id));
            });
            params.articleOrganizationIds = organizationIds;
          }

          const response = await pageCuesActive({
            createdSource: 1,
            ...queryParam,
            ...params,
          });

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        rowKey="id"
        dateFormatter="string"
        bordered
        search={false}
        sticky
        ghost
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        headerTitle={
          <div
            style={{
              display: 'flex',
            }}
          >
            <Input.Search
              placeholder="查询标题"
              enterButton="搜索"
              allowClear
              style={{ maxWidth: 250, width: '100%' }}
              onChange={(e) => {
                setQueryParamState({ ...queryParam, articleName: e.target.value });
              }}
              onSearch={(value) => {
                actionRef.current?.reset();
              }}
            />
            <ProFormCascader
              width="xl"
              name="assignOrganizationIds"
              placeholder="选择单位"
              style={{
                padding: '10px',
              }}
              formItemProps={{
                style: {
                  width: width - 800,
                  marginLeft: '18px',
                  marginBottom: '0px',
                },
              }}
              fieldProps={{
                options: articleOrganizations,
                // showSearch: { filter },
                multiple: true,
                removeIcon: true,
                allowClear: true,
                maxTagCount: 'responsive',
                showCheckedStrategy: Cascader.SHOW_CHILD,
                onChange(value, selectOptions) {
                  setQueryParamState({ ...queryParam, articleOrganizationIds: value });
                  actionRef.current?.reset();
                },
              }}
            />
          </div>
        }
        toolbar={{
          filter: (
            <LightFilter
              onValuesChange={(value) => {
                setQueryParamState(value);
                actionRef?.current?.reset();
              }}
            >
              <ProFormDateRangePicker
                name="createdTimes"
                label="创建日期"
                allowClear
                fieldProps={{
                  allowClear: true,
                  placeholder: ['开始日期', '结束日期'],
                  format: 'YYYY-MM-DD',
                  ranges: {
                    今日: [moment(), moment()],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment().startOf('month').subtract(1, 'months'),
                      moment().endOf('month').subtract(1, 'months'),
                    ],
                    最近7天: [moment().subtract(6, 'days'), moment()],
                    最近60天: [moment().subtract(59, 'days'), moment()],
                    最近90天: [moment().subtract(89, 'days'), moment()],
                  },
                }}
              />
            </LightFilter>
          ),
        }}
      />
    </PageContainer>
  );
};
export default Active;
